<?
class Model_Db extends Zend_Db_Table_Abstract{

	protected $_name = 'post';
    
    protected $_usePostId = null;
    
    public $_useSourceId = 1;
	
    /**
     * Ищем ID поста в базе
     */
	public function FindId( $id ){
	
		$id = intval($id);
		
		$select = $this->select()->where('source_id = ?', $this->_useSourceId)->where('external_id = ?', $id);
        
        $result = $this->fetchRow($select);
        
        if(null !== $result){
            $this->_usePostId = $id;
            return true;
        }
        
        return false;
	
	}
    
    /**
     * Обновляем рейтинг поста
     */
    public function RatingUpdate($rate, $date){
        
        if(null === $this->_usePostId){
            return false;
        }
        
        $data = array(
            'external_rating'=>$rate,
            'external_created_at'=>$date
        );
        
        $this->update($data, array($this->getAdapter()->quoteInto('source_id = ?', $this->_useSourceId), $this->getAdapter()->quoteInto('external_id = ?', $this->_usePostId)));
        
    }
    
    /**
     * Добавление поста
     */
    public function AddPost($data = array()){
        
        $columns = $this->info();
        
        $insertData = array();
        foreach($columns['metadata'] as $column=>$metadata){
            if($column === 'created_at'){
                $insertData[$column] = date('Y-m-d H:i:s');
            }elseif($column === 'modified_at'){
                $insertData[$column] = time();
            }else{            
                $insertData[$column] = (isset($data[$column])) ? $data[$column] : '';
            }
        }
        
        return $this->insert($insertData);
        
    }

}